/*
 * Copyright 2020 The edap Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package io.edap.protobuf.ext.codec;

import io.edap.protobuf.EncodeException;
import io.edap.protobuf.ProtoBufException;
import io.edap.protobuf.ProtoBufReader;
import io.edap.protobuf.ProtoBufWriter;
import io.edap.protobuf.ext.ExtCodec;

import static io.edap.protobuf.ext.AnyCodec.RANGE_INT_END;
import static io.edap.protobuf.ext.AnyCodec.RANGE_INT_START;


/**
 * 整数的编解码器
 */
public class IntegerCodec implements ExtCodec<Integer> {

    private Integer val;
    public IntegerCodec() {

    }

    public IntegerCodec(Integer val) {
        this.val = val;
    }

    @Override
    public Integer decode(ProtoBufReader reader) throws ProtoBufException {
        if (null != val) {
            return val;
        }
        return reader.readSInt32();
    }

    @Override
    public void encode(ProtoBufWriter writer, Integer v) throws EncodeException {
        if (v >= RANGE_INT_START && v < RANGE_INT_END) {
            writer.writeInt32(v, true);
            return;
        }
        if (writer.getWriteOrder() == ProtoBufWriter.WriteOrder.SEQUENTIAL) {
            writer.writeByte((byte)RANGE_INT_END);
            writer.writeSInt32(v, true);
        } else {
            writer.writeSInt32(v, true);
            writer.writeByte((byte)RANGE_INT_END);
        }
    }
}
